/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package frontera;

import Control.CrudCliente;
import Control.CrudCompra;
import Control.CrudProducto;
import Entidad.Cliente;
import Entidad.Producto;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import javax.swing.DefaultCellEditor;
import javax.swing.JComboBox;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;

/**
 *
 * @author PC
 */
public class CrearCompras extends javax.swing.JFrame {

    /**
     * Creates new form CrearCompras
     */
    public CrearCompras() {
        initComponents();
        this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        inicializar();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel7 = new javax.swing.JLabel();
        PPresupuesto = new javax.swing.JPanel();
        BAgregarProducto = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        TProductos = new javax.swing.JTable();
        BEliminarProducto = new javax.swing.JButton();
        realizarCompraB = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        valorL = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        fechaL = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        IdClienteTF = new javax.swing.JTextField();
        buscarB = new javax.swing.JButton();
        nombreTF = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        Direccion = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        direccionTF = new javax.swing.JTextField();
        telefonoTF = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        emailTF = new javax.swing.JTextField();
        crearCleinteB = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Nueva Compra", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, null, new java.awt.Color(255, 0, 0)));

        jLabel7.setText("Fecha:");

        PPresupuesto.setBorder(javax.swing.BorderFactory.createTitledBorder("Productos"));

        BAgregarProducto.setText("Agregar Producto");
        BAgregarProducto.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BAgregarProductoActionPerformed(evt);
            }
        });

        TProductos.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null}
            },
            new String [] {
                "Nombre", "ID", "Valor", "Garantia"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Object.class, java.lang.Integer.class, java.lang.Double.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                true, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        TProductos.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                TProductosMouseClicked(evt);
            }
        });
        jScrollPane2.setViewportView(TProductos);

        BEliminarProducto.setText("Eliminar Producto");
        BEliminarProducto.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BEliminarProductoActionPerformed(evt);
            }
        });

        realizarCompraB.setText("Realizar Compra");
        realizarCompraB.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                realizarCompraBActionPerformed(evt);
            }
        });

        jLabel3.setText("Valor Compra:");

        valorL.setText("0.0");

        jLabel8.setText("$");

        javax.swing.GroupLayout PPresupuestoLayout = new javax.swing.GroupLayout(PPresupuesto);
        PPresupuesto.setLayout(PPresupuestoLayout);
        PPresupuestoLayout.setHorizontalGroup(
            PPresupuestoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(PPresupuestoLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(PPresupuestoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(PPresupuestoLayout.createSequentialGroup()
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 430, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 28, Short.MAX_VALUE)
                        .addGroup(PPresupuestoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(BEliminarProducto, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(BAgregarProducto, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(realizarCompraB, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 115, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(PPresupuestoLayout.createSequentialGroup()
                        .addComponent(jLabel3)
                        .addGap(32, 32, 32)
                        .addComponent(jLabel8)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(valorL, javax.swing.GroupLayout.PREFERRED_SIZE, 107, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        PPresupuestoLayout.setVerticalGroup(
            PPresupuestoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(PPresupuestoLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(PPresupuestoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(PPresupuestoLayout.createSequentialGroup()
                        .addComponent(BAgregarProducto)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(BEliminarProducto)
                        .addGap(85, 85, 85)
                        .addComponent(realizarCompraB))
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 165, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(PPresupuestoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(valorL)
                    .addComponent(jLabel8))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jLabel1.setText("ID Cliente:");

        buscarB.setText("Buscar");
        buscarB.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buscarBActionPerformed(evt);
            }
        });

        jLabel2.setText("Nombre:");

        Direccion.setText("Direccion:");

        jLabel4.setText("Telefono:");

        direccionTF.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                direccionTFActionPerformed(evt);
            }
        });

        jLabel5.setText("email:");

        crearCleinteB.setText("Crear Cliente");
        crearCleinteB.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                crearCleinteBActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(25, 25, 25)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addComponent(jLabel2)
                            .addComponent(Direccion)
                            .addComponent(jLabel4))
                        .addGap(33, 33, 33)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                                .addComponent(IdClienteTF, javax.swing.GroupLayout.PREFERRED_SIZE, 182, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(buscarB, javax.swing.GroupLayout.PREFERRED_SIZE, 109, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                                .addComponent(telefonoTF, javax.swing.GroupLayout.PREFERRED_SIZE, 104, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 34, Short.MAX_VALUE)
                                .addComponent(jLabel5)
                                .addGap(29, 29, 29)
                                .addComponent(emailTF, javax.swing.GroupLayout.PREFERRED_SIZE, 157, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(nombreTF)
                            .addComponent(direccionTF))
                        .addGap(18, 18, 18)
                        .addComponent(crearCleinteB, javax.swing.GroupLayout.PREFERRED_SIZE, 119, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel7)
                                .addGap(18, 18, 18)
                                .addComponent(fechaL, javax.swing.GroupLayout.PREFERRED_SIZE, 208, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(PPresupuesto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jLabel7, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(fechaL, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGap(18, 18, 18)
                .addComponent(PPresupuesto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(IdClienteTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(buscarB)
                    .addComponent(crearCleinteB))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(nombreTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addGap(23, 23, 23)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(direccionTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(Direccion))
                .addGap(19, 19, 19)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(telefonoTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5)
                    .addComponent(emailTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, 0))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void direccionTFActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_direccionTFActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_direccionTFActionPerformed

    private void realizarCompraBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_realizarCompraBActionPerformed
        // TODO add your handling code here:
        double precio=0;
        ArrayList<Producto> productos= new ArrayList();
        for (int i=0;i<TProductos.getRowCount();i++){
        Producto pro = CrudProducto.ConsultarProducto(TProductos.getValueAt(i,0).toString());
        productos.add(pro);
        TProductos.setValueAt(pro.getID(),i,1);
        TProductos.setValueAt(pro.getValor(),i,2);
        TProductos.setValueAt(pro.getGarantia(),i,3);
       
        String t =TProductos.getValueAt(i, 2).toString();
        precio=precio+ Double.parseDouble(t);
        }
        valorL.setText(Double.toString(precio));
        try{ 
            Cliente cliente = CrudCliente.consultarCliente(Double.parseDouble(IdClienteTF.getText()));
           if (CrudCompra.crearCompra(Double.parseDouble(valorL.getText()),fechaL.getText(),productos,cliente)){
            JOptionPane.showMessageDialog(this, "Compra realizada exitosamente");
            DefaultTableModel modelo = (DefaultTableModel)TProductos.getModel();
                        
            for(int i=0;i<TProductos.getRowCount();i++){
            modelo.removeRow(i);
            }
            inicializar();
            
        }
            else                
            JOptionPane.showMessageDialog(this, "Ingrese el Id de un cliente existente");
            
        }catch(Exception e){
        }
       
    

    
    }//GEN-LAST:event_realizarCompraBActionPerformed

    private void BEliminarProductoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BEliminarProductoActionPerformed
        DefaultTableModel modelo = (DefaultTableModel)TProductos.getModel();
        int filaActual;
        try{
            filaActual = TProductos.getSelectedRow();
            modelo.removeRow(filaActual);
        }
        catch (Exception e){
            JOptionPane.showMessageDialog(null, "Seleccione el Rubro que desea eliminar");
        }
    }//GEN-LAST:event_BEliminarProductoActionPerformed

    private void TProductosMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_TProductosMouseClicked

    }//GEN-LAST:event_TProductosMouseClicked

    private void BAgregarProductoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BAgregarProductoActionPerformed
        DefaultTableModel modelo = (DefaultTableModel)TProductos.getModel();
        modelo.addRow(new String[3]);
        TProductos.setValueAt(0,TProductos.getRowCount()-1, 2);
        TProductos.setValueAt(0,TProductos.getRowCount()-1, 1);
        TProductos.setValueAt("0 meses",TProductos.getRowCount()-1, 3);

        double precio=0;
        for (int i=0;i<TProductos.getRowCount()-1;i++){
        try{
            Producto pro = CrudProducto.ConsultarProducto(TProductos.getValueAt(i,0).toString());
            TProductos.setValueAt(pro.getID(),i,1);
            TProductos.setValueAt(pro.getValor(),i,2);
            TProductos.setValueAt(pro.getGarantia(),i,3);  
            String t =TProductos.getValueAt(i, 2).toString();
            precio=precio+ Double.parseDouble(t);
        }
        catch(Exception e){
            System.out.print("exception");
            e.printStackTrace();
        }
        
        }
        valorL.setText(Double.toString(precio));

    }//GEN-LAST:event_BAgregarProductoActionPerformed

    private void buscarBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buscarBActionPerformed
        // TODO add your handling code here:
       try{ 
       Cliente cliente = CrudCliente.consultarCliente(Double.parseDouble(IdClienteTF.getText()));
       nombreTF.setText(cliente.getNombre());
       direccionTF.setText(cliente.getDireccion());
       telefonoTF.setText(Integer.toString(cliente.getTelefono()));
       emailTF.setText(cliente.getEmail());
       nombreTF.setText(cliente.getNombre());
       
       }    
       catch(Exception e){
       JOptionPane.showMessageDialog(this, "Cliente inexistente");
       nombreTF.setText("");
       direccionTF.setText("");
       telefonoTF.setText("");
       emailTF.setText("");
       nombreTF.setText("");
       crearCleinteB.setVisible(true);
       }
       
    }//GEN-LAST:event_buscarBActionPerformed

    private void crearCleinteBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_crearCleinteBActionPerformed
        // TODO add your handling code here:
        try{
            if (CrudCliente.crearCliente(nombreTF.getText(),  Double.parseDouble(IdClienteTF.getText()), direccionTF.getText(), Integer.parseInt(telefonoTF.getText()),emailTF.getText()))  {        
            JOptionPane.showMessageDialog(this, "Cliente creado exitosamente");
            PanelCliente.dtmclientes.addRow(new Object[] { nombreTF.getText(),  Double.parseDouble(IdClienteTF.getText()), direccionTF.getText(), (Integer.parseInt(telefonoTF.getText())),emailTF.getText()});
            }else
            JOptionPane.showMessageDialog(this, "Cliente no creado");
            

        
        }
        catch(Exception e){
            System.out.print("exception");
            e.printStackTrace();
        }
        
    }//GEN-LAST:event_crearCleinteBActionPerformed

    /**
     * @param args the command line arguments
     */
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton BAgregarProducto;
    private javax.swing.JButton BEliminarProducto;
    private javax.swing.JLabel Direccion;
    private javax.swing.JTextField IdClienteTF;
    private javax.swing.JPanel PPresupuesto;
    private javax.swing.JTable TProductos;
    private javax.swing.JButton buscarB;
    private javax.swing.JButton crearCleinteB;
    private javax.swing.JTextField direccionTF;
    private javax.swing.JTextField emailTF;
    private javax.swing.JLabel fechaL;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTextField nombreTF;
    private javax.swing.JButton realizarCompraB;
    private javax.swing.JTextField telefonoTF;
    private javax.swing.JLabel valorL;
    // End of variables declaration//GEN-END:variables

    private void inicializar() {
        
        nombreTF.setText("");
        direccionTF.setText("");
        telefonoTF.setText("");
        emailTF.setText("");
        nombreTF.setText("");
        IdClienteTF.setText("");
        Date fecha=new Date(); 
        SimpleDateFormat sdf=new SimpleDateFormat("dd/MM/yyyy"); 
        fechaL.setText(sdf.format(fecha));
        TProductos.setValueAt(0,0, 2);
        TProductos.setValueAt(0,0, 1);
        TProductos.setValueAt("0 meses",0, 3);
        JComboBox listpro = new JComboBox();
        listpro.removeAllItems();
        List<Producto> productos = CrudProducto.bringAll();
        for (int i=0; i<productos.size(); i++){
            listpro.addItem(productos.get(i).getNombre());
        }
        TableColumn col=TProductos.getColumnModel().getColumn(0);
        col.setCellEditor(new DefaultCellEditor(listpro));
        crearCleinteB.setVisible(false);
        
        
    }
}
